<template>
	<view class="login-container">
		<!-- 登录组件 -->
		<uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
		<button type="warn" class="btn-login" open-type="getUserInfo" @getuserinfo="getUserInfo">一键登录</button>
		<!-- <button type="warn" class="btn-login" @click="getUserProfile">一键登录</button> -->
		<text class="tips-text">登陆后尽享更多权益</text>
	</view>
</template>

<script>
	import {mapState,mapMutations} from 'vuex'
	export default {
		name:"my-login",
		data() {
			return {
				
			};
		},
		methods:{
			//用户授权后获取用户的基本信息
			getUserInfo(e){
				console.log(e)
				if(e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('取消了登录授权')
				console.log(e.detail.userInfo)
				this.updateUserInfo(e.detail.userInfo)
				
				this.getToken(e.detail)
			},
			async getToken(info){
				// 获取code对应的值
				const [err,res] = await uni.login().catch(err => err)
				console.log(err,res)
				if(err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败')
				//如果uni.login获取code成功的话，准备一个参数对象
				const query = {
					code:res.code,
					encryptedData:info.encryptedData,
					iv:info.iv,
					rawData:info.rawData,
					signature:info.signature
				}
				
				console.log(query)
				const {data: loginResult} = await uni.$http.post('/api/public/v1/users/wxlogin', query)
				console.log(loginResult)
				//这里是教程的服务器有问题，所以会返回400状态码，获取不到数据
				if(loginResult.meta.status !== 200 && loginResult.meta.status !== 400) return uni.$showMsg('post请求失败，未获得数据')
				uni.$showMsg('登录成功')
				//将token保存到vuex中
				this.updateToken('123')
				//登陆成功后进行跳转回购物车
				this.navigateBack();
			},
			navigateBack(){
				//如果有返回的地址和返回方式为switchTab
				if(this.redirectInfo && this.redirectInfo.openType === 'switchTab'){
					uni.switchTab({
						url:this.redirectInfo.from,
						//complete调用结束后执行的回调函数，必定执行
						complete: () => {
							this.updateRedirectInfo(null)
						}
					})
				}
			},
			// getUserProfile(e){
			// 	uni.getUserProfile({
			// 		desc:e
			// 	})
			// }
			...mapMutations('m_address',['updateUserInfo','updateToken','updateRedirectInfo'])
		},
		computed:{
			...mapState('m_address',['redirectInfo'])
		}
	}
</script>

<style lang="scss">
.login-container{
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	height: 750rpx;
	background-color: #f8f8f8;
	position: relative;
	overflow: hidden;
	
	&::after{
		content: ' ';
		width: 100%;
		height: 40px;
		border-radius: 100%;
		position: absolute;
		bottom: 0;
		left: 0;
		background-color: #fff;
		transform: translateY(50%);
	}
	.btn-login{
		width: 300px;
		height: 50px;
		border-radius: 25px;
		margin: 15px 0;
		letter-spacing: 4px;
	}
	.tips-text{
		font-size: 12px;
		color: gray;
	}
}
</style>
